#include <iostream>
#include<stdio.h>
#include<pthread.h>
#include<string>
#include<unistd.h>
#define NUM 5
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ticket =10000;
void* start_routine(void* arg)
{
    std::string username = static_cast<const char*>(arg);
    while(true)
        {
            if(ticket>0)
            {
                // 加锁
                pthread_mutex_lock(&mutex);
                // 使用条件变量同步
                pthread_cond_wait(&cond,&mutex);
                std::cout<<username <<"->"<<"抢票成功"<<"余票还剩： "<<ticket<<std::endl;
                ticket--;
                pthread_mutex_unlock(&mutex);
            }
        }

}
int main()
{
    // 准备创建5个线程
    pthread_t id[NUM];
    for(int i=0;i<NUM;i++)
    {
        char *buffer = new char[64];;
        snprintf(buffer,64,"thread %d",i);
        pthread_create(id+i,nullptr,start_routine,buffer);  
    }
    // 创建完成
    while (true)
    {
        sleep(1);
        pthread_cond_signal(&cond);
        // pthread_cond_broadcast(&cond);
        std::cout << "main thread wakeup one thread..." << std::endl;
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(id[i], nullptr);
    }

    return 0;
}